package com.topisv.tms.service.work.ExceptionOrder;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.ExceptionOrder.ExceptionOrder;
import com.topisv.tms.entity.work.ExceptionOrder.ExceptionBackItem;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.repository.work.ExceptionOrder.ExceptionOrderDao;
import com.topisv.tms.repository.work.ExceptionOrder.ExceptionBackItemDao;

/**
 * 异常单退回商品明细_service
 * @author ch
 */
@Component
@Transactional(readOnly = true)
public class ExceptionBackItemService {

	@Autowired
	private ExceptionBackItemDao exceptionBackItemDao;
	@Autowired
	private ExceptionOrderDao exceptionOrderDao;
	@Autowired
	private WorkOrderDao workOrderDao;

	/**
	 * 查询
	 * @param exceptionId
	 * @return
	 */
	public List<ExceptionBackItem> loadByExceptionId(Long exceptionId) {
		return this.exceptionBackItemDao.loadByExceptionId(exceptionId);
	}

	/**
	 * 质检
	 * @param exceptionId
	 * @param sku
	 * @param errorFlag
	 * @param num
	 * @return
	 */
	@Transactional(readOnly = false)
	public String qc(Long exceptionId, String sku, String batchCode, String productDate, String expireDate, String errorFlag, int num) {
		String msg="success";
		try {
			ExceptionBackItem qi=this.exceptionBackItemDao.loadByConditionNew(exceptionId,errorFlag,sku,batchCode,productDate,expireDate);
			if(qi==null){
				ExceptionOrder eOrder=this.exceptionOrderDao.findOne(exceptionId);
				qi=new ExceptionBackItem();
				qi.setErrorFlag(errorFlag);
				qi.setNum(0);
				qi.setSku(sku);
				qi.setBatchCode(batchCode);
				qi.setProductDate(productDate);
				qi.setExpireDate(expireDate);
				qi.setOrderno(eOrder.getOrderno());
				qi.setExceptionId(exceptionId);
			}
			String orderno = qi.getOrderno();
			//校验sku是否正确
			WorkOrder workOrder = workOrderDao.loadByOrderno(orderno);
			String reg = "(^|\\S+;)"+sku+":\\S+";
			if (!workOrder.getGoodsInfo().matches(reg)) {
				msg = "notmatch";
			} else {
				//modify 20160620 lianghe.yuan
				//qi.setNum(qi.getNum() + 1);
				qi.setNum(qi.getNum() + num);
				this.exceptionBackItemDao.save(qi);
			}
			
		} catch (Exception e) {
			msg="error";
		}
		return msg;
	}

	/**
	 * 删除
	 * @param itemId
	 */
	@Transactional(readOnly = false)
	public void deleteQcItem(Long itemId) {
		this.exceptionBackItemDao.delete(itemId);
	}

}